﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace Twi.COMMON.Core
{
    /**
     * Copyright: ©2015 踏影软件开发工作室【Tyingsoft、Twilight】版权所有
     * Author: feitianxinhong
     * Create Date: 2015-04-24
     * Description: XmlElement 扩展方法
     *
     */
    public static class ExtensionXmlElement
    {
        /// <summary>
        /// 根据节点名称获取节点值（节点名不存在或者为空，返回默认值）
        /// </summary>
        /// <param name="xmlEl"></param>
        /// <param name="name">节点名称</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static string GetTextByName(this XmlElement xmlEl, string name,string defaultValue=null) 
        {
            if (xmlEl[name] != null) 
            {
                string text = xmlEl[name].InnerText.Trim();
                if (!string.IsNullOrEmpty(text)) 
                {
                    return text;
                }  
            }
            return defaultValue;
        }

        /// <summary>
        /// 根据属性名获取属性值（属性不存在或者为空，返回默认值）
        /// </summary>
        /// <param name="xmlEl"></param>
        /// <param name="name">属性名称</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static string GetAttributeByName(this XmlElement xmlEl, string name, string defaultValue = null) {
            if (xmlEl.HasAttribute(name)) 
            {
                string value = xmlEl.Attributes[name].InnerText.Trim();
                if (!string.IsNullOrEmpty(value))
                {
                    return value;
                }  
            }
            return defaultValue;
        }

        /// <summary>
        /// 将XmlElement对象转化为XElement对象
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public static XElement ToXElement(this XmlElement xmlEl)
        {
            XDocument xDoc = new XDocument();
            using (XmlWriter xmlWriter = xDoc.CreateWriter())
            {
                xmlEl.WriteTo(xmlWriter);
            }
            return xDoc.Root;
        }
    }
}
